package tool;

import cn.hutool.core.lang.Singleton;
import constant.ConfigConstants;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.io.*;

/**
 * Created by Intellij IDEA.
 * User:  老赵
 * Date:  2023/7/10
 */
public class Ocr {

    private static Button uploadButton;
    private static ImageView imageView;
    private static TextArea textArea;
    private static TextField tessdataField;
    private static String language = "chi_sim";
    private static Tesseract iTesseract;

    public static void openOCRStage() {
        Stage stature = new Stage();
        stature.setTitle("OCR文字识别");
        stature.setFullScreen(ConfigConstants.FullScreen);

        GridPane gridPane = new GridPane();
        gridPane.setPadding(new Insets(10)); // 设置内边距为10像素
        gridPane.setVgap(10); // 设置垂直间距为10像素
        gridPane.setHgap(10); // 设置水平间距为10像素
        ColumnConstraints column1 = new ColumnConstraints();
        column1.setPercentWidth(30);
        ColumnConstraints column2 = new ColumnConstraints();
        column2.setPercentWidth(70);
        gridPane.getColumnConstraints().addAll(column1, column2);

        Label cityLabel = new Label("本地语言库地址:");
        tessdataField = new TextField();
        tessdataField.setText("D:\\AAA\\work_other\\yuBo_javaFX\\doc\\tessdata");
        gridPane.addRow(0,cityLabel,tessdataField);

        uploadButton = new Button("上传图片");
        uploadButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                String tessdataPath = tessdataField.getText();
                File folder = new File(tessdataPath);
                if (folder.exists() && folder.isDirectory()) {
                    handleUpload();
                } else {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("警告");
                    alert.setHeaderText(null);
                    alert.setContentText("未检测本地tessdata语言库，请看README.md中安装教程");
                    alert.showAndWait();
                }
            }
        });

        imageView = new ImageView();

        Label viewLabel = new Label("OCR识别内容:");

        textArea = new TextArea();
        textArea.setEditable(false);
        textArea.setWrapText(true);
        textArea.setMinWidth(300);
        textArea.setMinHeight(300);

        gridPane.addRow(1,uploadButton);
        gridPane.addRow(2, imageView);
        gridPane.addRow(3, viewLabel);
        gridPane.addRow(4, textArea);

        Scene scene = new Scene(gridPane, 500, 700);
        stature.setScene(scene);
        stature.show();
    }

    private static void handleUpload() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.jpeg"));
        File file = fileChooser.showOpenDialog(null);

        if (file != null) {
            Image image = new Image(file.toURI().toString());
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(image.getWidth()/2);
            imageView.setFitHeight(image.getHeight()/2);
            imageView.setImage(image);

            String recognizedText = performOCR(file);
            textArea.setText(recognizedText);
        } else {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText("未检测到任何图片文件");
            alert.showAndWait();
        }
    }

    private static String performOCR(File file) {
        iTesseract = Singleton.get(Tesseract.class);
        iTesseract.setLanguage(language);
        iTesseract.setDatapath(tessdataField.getText());
        String doOCR;
        try {
            doOCR = iTesseract.doOCR(file);
        } catch (TesseractException e) {
            throw new RuntimeException(e);
        }
        return doOCR;
    }
}
